package com.sxj.corejava.code01_线程;

/**
 * @author 石小俊
 * @date 2023年11月2023/11/16日 18:26
 */
public class Test07_线程间的通信 {

    public static void main(String[] args) {
        // 等待线程
        Object obj = new Object();
        WaitThread t1 = new WaitThread(obj,"线程1");
        t1.start();
        WaitThreadTwo t2 = new WaitThreadTwo(obj,"线程2");
        t2.start();

        // 随机唤醒线程
//        NotifyThread notifyThread = new NotifyThread(obj,"notify线程");
//        notifyThread.start();
//        Object obj2 = new Object();
        NotifyAllThread all = new NotifyAllThread(obj,"notifyAll线程");
        all.start();
    }

}

class WaitThread extends Thread {
    private Object obj;
    private String name;

    public WaitThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            System.out.println(name + "释放锁,即将进入等待池");
            try {
                // 使得线程放弃对象锁,进入到等待池
                // 此时可以设置等待时间,也可以不设置等待时间
                // 如果设置等待时间,则达到等待时间之后自动唤醒
                // 如果不设置等待时间,必须由其他线程唤醒
//                obj.wait(3000);
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + "执行完成");
        }
    }
}

class WaitThreadTwo extends Thread {
    private Object obj;
    private String name;

    public WaitThreadTwo(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            System.out.println(name + "释放锁,即将进入等待池");
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + "执行完成");
        }
    }
}

class NotifyThread extends Thread{
    private Object obj;
    private String name;

    public NotifyThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj){
            // 随机唤醒某一个线程
            // 此时唤醒的是当前对象的等待池中的线程
            // 即:obj对象的等待池中的线程
            obj.notify();
            System.out.println("已经随机唤醒了当前等待池中的某一个线程");
        }
    }
}

class NotifyAllThread extends Thread{
    private Object obj;
    private String name;

    public NotifyAllThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj){
            // 唤醒所有线程
            // 此时唤醒的是当前对象的等待池中的所有线程
            // 即:obj对象的等待池中的线程
            obj.notifyAll();
            System.out.println("已经唤醒了当前等待池中的所有线程");
        }
    }
}
